package com.promise.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.promise.controller.result.RecordResult;
import com.promise.pojo.Record;
import com.promise.service.RecordServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/records")
public class RecordController {
    @Autowired
    private RecordServiceImpl recordService;

    /**
     * 分页查询记录
     *
     * @param currentPage 当前页码
     * @param pageSize    页面数据条数
     * @param searchData  搜索条件
     * @return RecordResult 分页查询结果
     */
    @PostMapping("/{currentPage}/{pageSize}")
    @ResponseBody
    public RecordResult getRecordByPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize,
                                        @RequestBody Record searchData) {
        // 查询条件(故障内容，是否警告，是否处理)
        LambdaQueryWrapper<Record> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(searchData.getRecordDate()),
                        Record::getRecordDate, searchData.getRecordDate())
                .eq(!StringUtils.isEmpty(searchData.getWarning()),
                        Record::getWarning, searchData.getWarning())
                .eq(!StringUtils.isEmpty(searchData.getWatchName()),
                        Record::getWatchName, searchData.getWatchName());

        IPage<Record> iPage = new Page<>(currentPage, pageSize);
        IPage<Record> page = recordService.page(iPage, queryWrapper);
        Integer code = page.getRecords() != null ? Code.SUCCESS_CODE : Code.ERROR_CODE;
        String msg = page.getRecords() != null ? "查询成功" : "查询失败";

        Map<String, Object> data = new HashMap<>();
        data.put("pages", page.getPages());
        data.put("currentPage", page.getCurrent());
        data.put("pageSize", page.getSize());
        data.put("records", page.getRecords());
        data.put("total", page.getTotal());
        return new RecordResult(code, data, msg);

    }

    /**
     * 根据recordId删除
     *
     * @param recordId id
     * @return RecordResult
     */
    @DeleteMapping("delete/{recordId}")
    @ResponseBody
    public RecordResult delete(@PathVariable Integer recordId) {
        boolean flag = recordService.removeById(recordId);
        Integer code = flag ? Code.SUCCESS_CODE : Code.ERROR_CODE;
        String msg = flag ? "删除成功" : "删除失败";
        return new RecordResult(code, flag, msg);
    }


    /**
     * 根据recordId更新记录
     *
     * @param recordId     记录的ID
     * @param updatedRecord 包含更新信息的记录对象
     * @return RecordResult 更新结果
     */
    @PutMapping("update/{recordId}")
    @ResponseBody
    public RecordResult update(@PathVariable Integer recordId, @RequestBody Record updatedRecord) {
        if (updatedRecord == null || !recordId.equals(updatedRecord.getRecordId())) {
            return new RecordResult(Code.ERROR_CODE, false, "更新失败，记录ID不匹配或记录对象为空");
        }

        boolean updated = recordService.updateById(updatedRecord);
        Integer code = updated ? Code.SUCCESS_CODE : Code.ERROR_CODE;
        String msg = updated ? "更新成功" : "更新失败";

        return new RecordResult(code, updated, msg);
    }


    /**
     * 新增记录
     *
     * @param record 要新增的记录对象
     * @return RecordResult 新增操作结果
     */
    @PostMapping("/add")
    @ResponseBody
    public RecordResult addRecord(@RequestBody Record record) {
        try {
            boolean result = recordService.save(record);
            Integer code = result ? Code.SUCCESS_CODE : Code.ERROR_CODE;
            String msg = result ? "新增成功" : "新增失败";
            return new RecordResult(code, result, msg);
        } catch (Exception e) {
            // 处理异常情况，例如记录数据不符合要求等
            Integer code = Code.ERROR_CODE;
            String msg = "新增失败：" + e.getMessage();
            return new RecordResult(code, false, msg);
        }
    }
}
